//
//  NewFeatrueViewController.swift
//  01- 搭建框架
//
//  Created by apple on 15/10/19.
//  Copyright © 2015年 任伟. All rights reserved.
//

import UIKit

/// 可重用标识符
private let WBNewFeatureViewCellID = "WBNewFeatureViewCellID"
///新特性图片的数量
private let WBNewFeatureCount = 4

class NewFeatrueViewController: UICollectionViewController {

    /// MARK: -构造函数
    init() {
        
        //设置自动布局
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .Horizontal
        
        //构造函数,完成之后内部的属性才会被创建
        super.init(collectionViewLayout:layout)
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }

    ///隐藏状态栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置 collectionView 的 背景颜色
       // collectionView?.backgroundColor = UIColor.whiteColor()
        
        // Register cell classes
        collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: WBNewFeatureViewCellID)
    }

    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return WBNewFeatureCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
       let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBNewFeatureViewCellID, forIndexPath: indexPath) as! NewFeatureCell
        
        cell.imageIndex = indexPath.item
        
        return cell
    }
    
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 再最后一页才调用动画方法
        // 根据 contentOffset 计算页数
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        // 判断是否是最后一页
        if page != WBNewFeatureCount - 1 {
            return
        }
        
        // Cell 播放动画
        let cell = collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: page, inSection: 0)) as! NewFeatureCell
        
        // 显示动画
        cell.showButtonAnim()
    }
}

    
/// MARK: - 新特性 Cell
    private class NewFeatureCell: UICollectionViewCell {
    
        /// 图像的属性
        var imageIndex: Int = 0 {
            didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
                
                //隐藏按钮
                startButton.hidden = true
            }
        }
        
        ///点击开始体验按钮
        @objc private func clickStartButton() {
        
            print("开始体验")
            
            //发出通知
            NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: nil)
        }
        
        /// 显示按钮动画
        private func showButtonAnim() {
            startButton.hidden = false
            startButton.transform = CGAffineTransformMakeScale(0, 0)
            startButton.userInteractionEnabled = false
            
            UIView.animateWithDuration(1.6,     // 动画时长
                delay: 0,                       // 延时时间
                usingSpringWithDamping: 0.6,    // 弹力系数，0~1，越小越弹
                initialSpringVelocity: 10,      // 初始速度，模拟重力加速度
                options: [],                    // 动画选项
                animations: { () -> Void in
                    
                    self.startButton.transform = CGAffineTransformIdentity
                    
                }) { (_) -> Void in
                    self.startButton.userInteractionEnabled = true
            }
            
        }

    
        /// MARK: -设置界面
        override init(frame: CGRect) {
            super.init(frame: frame)
            
            setupUI()
        }

        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

    ///
        private func setupUI() {

            addSubview(iconView)
            addSubview(startButton)
        
            startButton.layer.cornerRadius = 5
            startButton.layer.masksToBounds = true
            
            iconView.frame = bounds
            
            startButton.snp_makeConstraints { (make) -> Void in
                make.centerX.equalTo(self.snp_centerX)
                make.bottom.equalTo(self.snp_bottom).multipliedBy(0.7)
            }
            
            //开始体验监听按钮
            startButton.addTarget(self, action: "clickStartButton", forControlEvents: .TouchUpInside)
        }
    /// MARK: - 懒加载控件
    /// 图像
    private lazy var iconView = UIImageView()
    ///开始点击按钮
    private lazy var startButton: UIButton = UIButton(title: "开始体验", color: UIColor.whiteColor(), imageName: "new_feature_finish_button")
}
